package com.byfan.barter.service.Impl;

import com.byfan.barter.entity.Favorites;
import com.byfan.barter.jpa.FavoritesJpa;
import com.byfan.barter.service.FavoritesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * @Author: FBY
 * @Description
 * @Version 1.0
 * @Date: 2021/5/14 15:49
 */
@Service
@Transactional
public class FavoritesServiceImpl implements FavoritesService {

    @Autowired
    private FavoritesJpa favoritesJpa;

    /**
     * 新增收藏
     * @param favorites
     * @return
     */
    @Override
    public Favorites save(Favorites favorites) {
        return favoritesJpa.save(favorites);
    }

    /**
     * 根据用户openid和商品id取消收藏
     * @param openId
     * @param commodityId
     */
    @Override
    public void delete(String openId, Integer commodityId) {
        favoritesJpa.deleteByOpenIdAndCommodityId(openId,commodityId);
    }

    /**
     * 根据收藏id进行取消收藏
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        favoritesJpa.deleteById(id);
    }

    /**
     * 根据id获取收藏信息
     * @param id
     * @return
     */
    @Override
    public Favorites getById(Integer id) {
        Optional<Favorites> optional = favoritesJpa.findById(id);
        if (optional.isPresent()){
            return optional.get();
        }
        return null;
    }

    /**
     * 根据用户openid获取所有收藏
     * @param openId
     * @return
     */
    @Override
    public List<Favorites> getByOpenId(String openId) {
//        Favorites favorites = new Favorites();
//        favorites.setOpenId(openId);
//        ExampleMatcher matcher = ExampleMatcher.matching()
//                .withIgnoreNullValues()
//                .withMatcher("openId",match -> match.exact());
//        Example example = Example.of(favorites,matcher);
//        return favoritesJpa.findAll(example);
        List<Favorites> result = favoritesJpa.findByOpenIdOrderByCreatTimeDesc(openId);
        return result.isEmpty()?null:result;
    }
}
